import os
from pathlib import Path
import configparser
from common.log import logger
from config.config import CONFIG_PATH


class IniOperate():
    def __init__(self, file_path):
        try:
            self.file_path = file_path
            if os.path.exists(file_path):
                self.file_path = str(file_path)
            else:
                logger.error(f"{file_path} doesn't exist.")
                raise FileNotFoundError(f"{file_path} doesn't exist.")
            self.config = configparser.ConfigParser()
            self.config.read(self.file_path, encoding="utf-8")
        except Exception as e:
            logger.error(f"{e}")

    def read_value(self, section_name, option_name) -> str:
        try:
            value = self.config.get(section_name, option_name)
            return value
        except Exception as e:
            section_exist = self.config.has_section(section_name)
            option_exist = self.config.has_option(section_name, option_name)
            if not section_exist:
                logger.error(f"Section '{section_name}' doesn't exist")
            elif not option_exist:
                logger.error(f"Option '{option_exist}' doesn't exist")
            return ""

    def modify_value(self, section_name: str, option_name: str, option_value: str):
        try:
            self.section_name = section_name
            self.option_name = option_name
            self.option_value = str(option_value)
            self.config.set(self.section_name, self.option_name, self.option_value)
            self.config.write(open(self.file_path, mode="w"))
        except Exception as e:
            section_exist = self.config.has_section(section_name)
            option_exist = self.config.has_option(section_name, option_name)
            if not section_exist:
                logger.error(f"Section '{section_name}' doesn't exist")
            elif not option_exist:
                logger.error(f"Option '{option_exist}' doesn't exist")


if __name__ == "__main__":
    ini = IniOperate(Path(CONFIG_PATH) / "config.ini")
    ini.modify_value("test", "cookies", "123")
